import React, { useEffect, useState } from 'react';
import { Download, ShoppingCart, ExternalLink, Mail, Phone } from 'lucide-react';
import { Language, Product } from '../../types';
import { useLanguage } from '../context/LanguageContext';
import { useConfig } from '../context/ConfigContext';
import { getProducts } from '../utils/productStorage';

const ProductsView: React.FC = () => {
  const { t, lang } = useLanguage();
  const { config } = useConfig();
  const [activeCategory, setActiveCategory] = useState<string>('all');
  const [selectedProduct, setSelectedProduct] = useState<Product | null>(null);
  const [products, setProducts] = useState<Product[]>([]);

  useEffect(() => {
    setProducts(getProducts());
  }, []);

  const categories = ['all', ...Array.from(new Set(products.map((p) => p.category)))];

  const filteredProducts = activeCategory === 'all' ? products : products.filter((p) => p.category === activeCategory);

  if (selectedProduct) {
    return (
      <div className="container mx-auto px-4 py-12">
        <button
          onClick={() => setSelectedProduct(null)}
          className="flex items-center gap-2 text-brand-stone hover:text-brand-orange mb-8 transition-colors font-bold"
        >
          &larr; {t.products.back}
        </button>

        <div className="grid md:grid-cols-2 gap-12">
          <div className="space-y-4">
            <img
              src={selectedProduct.images[0]}
              alt={selectedProduct.name[lang]}
              className="w-full h-[500px] object-cover rounded-2xl shadow-lg border border-gray-100"
            />
            <div className="grid grid-cols-3 gap-2">
              {selectedProduct.images.slice(1).map((img, idx) => (
                <img
                  key={idx}
                  src={img}
                  alt="Detail"
                  className="h-24 w-full object-cover rounded-lg cursor-pointer hover:opacity-80 border border-gray-100"
                />
              ))}
            </div>
          </div>

          <div className="space-y-8">
            <div>
              <h2 className="text-3xl font-serif font-bold text-brand-wood mb-2">{selectedProduct.name[lang]}</h2>
              <div className="inline-block bg-brand-cream px-4 py-1 rounded-full">
                <p className="text-2xl text-brand-orange font-bold">${selectedProduct.price.toFixed(2)}</p>
              </div>
            </div>

            <p className="text-gray-600 leading-relaxed text-lg font-sans">{selectedProduct.description[lang]}</p>

            <div className="flex flex-col gap-4 pt-8 border-t border-gray-100">
              <button
                onClick={() => alert('Payment Gateway Mock')}
                className="bg-brand-orange text-white py-4 rounded-xl flex items-center justify-center gap-2 hover:bg-orange-600 transition-colors font-bold text-lg shadow-md"
              >
                <ShoppingCart size={20} /> {t.products.buyNow}
              </button>

              <div className="grid grid-cols-2 gap-4">
                {selectedProduct.amazonLink && (
                  <a
                    href={selectedProduct.amazonLink}
                    target="_blank"
                    rel="noreferrer"
                    className="border-2 border-brand-stone/30 text-brand-stone py-3 rounded-xl flex items-center justify-center gap-2 hover:border-brand-orange hover:text-brand-orange transition-colors font-semibold"
                  >
                    <ExternalLink size={18} /> {t.products.buyAmazon}
                  </a>
                )}
                {selectedProduct.alibabaLink && (
                  <a
                    href={selectedProduct.alibabaLink}
                    target="_blank"
                    rel="noreferrer"
                    className="border-2 border-brand-stone/30 text-brand-stone py-3 rounded-xl flex items-center justify-center gap-2 hover:border-brand-orange hover:text-brand-orange transition-colors font-semibold"
                  >
                    <ExternalLink size={18} /> {t.products.buyAlibaba}
                  </a>
                )}
              </div>
            </div>

            <div className="bg-brand-cream p-6 rounded-xl mt-8 border border-brand-orange/10">
              <h4 className="font-serif text-lg text-brand-wood font-bold mb-2">{t.products.wholesaleTitle}</h4>
              <p className="text-sm text-gray-600 mb-4">{t.products.wholesaleText}</p>
              <div className="flex flex-col gap-2 text-sm font-medium">
                <div className="flex items-center gap-2 text-brand-stone">
                  <Mail size={16} /> {config.email}
                </div>
                <div className="flex items-center gap-2 text-green-600">
                  <Phone size={16} /> WhatsApp: {config.whatsapp}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="container mx-auto px-4 py-12">
      <div className="bg-brand-wood text-white p-10 rounded-2xl mb-16 text-center shadow-lg relative overflow-hidden">
        <div className="absolute top-0 left-0 w-full h-full opacity-10 bg-[url('https://www.transparenttextures.com/patterns/paw-prints.png')]"></div>
        <div className="relative z-10">
          <h3 className="text-2xl font-serif font-bold mb-6">{t.products.catalogTitle}</h3>
          <div className="flex flex-wrap justify-center gap-4">
            <a
              href={config.productCatalogs.en}
              target="_blank"
              rel="noopener noreferrer"
              className="flex items-center gap-2 bg-brand-orange hover:bg-orange-600 px-6 py-3 rounded-full transition-colors font-bold shadow-md"
            >
              <Download size={18} /> {t.products.downloadBtn} (EN)
            </a>
            <a
              href={config.productCatalogs.cn}
              target="_blank"
              rel="noopener noreferrer"
              className="flex items-center gap-2 bg-brand-orange hover:bg-orange-600 px-6 py-3 rounded-full transition-colors font-bold shadow-md"
            >
              <Download size={18} /> {t.products.downloadBtn} (CN)
            </a>
            <a
              href={config.productCatalogs.es}
              target="_blank"
              rel="noopener noreferrer"
              className="flex items-center gap-2 bg-brand-orange hover:bg-orange-600 px-6 py-3 rounded-full transition-colors font-bold shadow-md"
            >
              <Download size={18} /> {t.products.downloadBtn} (ES)
            </a>
          </div>
        </div>
      </div>

      <div className="flex justify-center gap-4 mb-12 flex-wrap">
        {categories.map((cat) => (
          <button
            key={cat}
            onClick={() => setActiveCategory(cat)}
            className={`px-6 py-2 rounded-full uppercase text-sm font-bold tracking-wider transition-all ${
              activeCategory === cat ? 'bg-brand-wood text-white shadow-md' : 'bg-brand-cream text-brand-stone hover:bg-brand-orange/20'
            }`}
          >
            {cat === 'all' ? t.products.categoryAll : cat}
          </button>
        ))}
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
        {filteredProducts.map((product) => (
          <div
            key={product.id}
            className="group bg-white rounded-2xl overflow-hidden shadow-sm hover:shadow-2xl transition-all duration-300 border border-gray-100 cursor-pointer"
            onClick={() => setSelectedProduct(product)}
          >
            <div className="h-72 overflow-hidden relative bg-gray-50">
              <img
                src={product.images[0]}
                alt={product.name[lang]}
                className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-500"
              />
              <div className="absolute inset-0 bg-black/20 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
                <span className="bg-brand-orange text-white px-6 py-2 rounded-full text-sm font-bold transform translate-y-4 group-hover:translate-y-0 transition-transform duration-300 shadow-md">
                  {t.products.detailsBtn}
                </span>
              </div>
            </div>
            <div className="p-6 text-center">
              <h3 className="text-lg font-serif font-bold text-brand-wood mb-2">{product.name[lang]}</h3>
              <p className="text-brand-orange font-bold text-xl">${product.price.toFixed(2)}</p>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

export default ProductsView;

